package com.ly.mpayment.rest.up.hubei;

import com.ly.mpayment.core.util.*;
import com.ly.mpayment.persist.entity.UpOrder;
import com.ly.mpayment.persist.entity.UpShopInfo;
import com.ly.mpayment.persist.entity.UpShopProduct;
import com.ly.mpayment.persist.service.downrechargeflow.IDownRechargeFlowService;
import com.ly.mpayment.persist.service.downshopinfo.IDownShopInfoService;
import com.ly.mpayment.persist.service.uporder.IUporderService;
import com.ly.mpayment.persist.service.upshopinfo.IUpShopInfoService;
import com.ly.mpayment.rest.recharge.RechargeRest;
import net.sf.json.JSONObject;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.log4j.Logger;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestBody;

import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.core.MediaType;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Component
@Path("hubeill")
public class HubeiRest {
    Logger logger = Logger.getLogger(HubeiRest.class);


    @Autowired
    IUporderService upOrderService;

    @Autowired
    IDownRechargeFlowService flowService;

    @Autowired
    IDownShopInfoService shopService;

    @Autowired
    IUpShopInfoService upShopInfoService;

    //private static String authUrl = "https://sc.4ggogo.com/web-in/auth.html";

    //private static String productsUrl = "https://sc.4ggogo.com/web-in/products.html";



    private static String token = "";
    private static String expiredTime = "";


    /**
     * 00	订单成功
     * 01	订单失败
     * 99	未知错误
     * @return
     */
    @Path("callBack")
    @POST
    @Consumes(MediaType.APPLICATION_XML)
    public synchronized String callBack(@RequestBody String body){
        logger.info("hubei_callBack:"+body);
        JSONObject json = JsonUtils.getJSONOBJCT();
        try {
            if (!StringUtils.isBlank(body)) {
                JsonUtils.iterateNodes(DocumentHelper.parseText(body).getRootElement(), json);
                if(json.containsKey("InterBOSS") && json.getJSONObject("InterBOSS").getJSONObject("Response").containsKey("RspCode")){
                    UpOrder order = upOrderService.findById(json.getJSONObject("InterBOSS").getString("TransIDO"));
                    logger.info("hubei_callBack:"+body+",order:"+order.getUpphonenum());
                    //充值结果状态，3：充值成功 4：充值失败
                    if (order != null && json.getJSONObject("InterBOSS").getJSONObject("Response").getString("RspCode").equals("00")
                            && order.getStatus() == Config.status[0]) {
                        order.setRemark(json.getJSONObject("InterBOSS").getJSONObject("Response").getString("RspDesc"));
                        RechargeRest.successUpOrder.add(order);
                        return createCall("00","成功",order.getUporderuuid());
                    }else if(order != null && order.getStatus() == Config.status[0] && json.getJSONObject("InterBOSS").getJSONObject("Response").getString("RspCode").equals("01")){
                        order.setRemark(json.getJSONObject("InterBOSS").getJSONObject("Response").getString("RspDesc"));
                        RechargeRest.failtUpOrder.add(order);
                        return createCall("00","成功",order.getUporderuuid());
                    }else{
                        logger.info("hubei_not_found_order:" + body +","+ (order == null ? " order is null" : order.getUpphonenum() ));
                    }
                }
                return createCall("99","成功",json.getJSONObject("InterBOSS").getString("TransIDO"));
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return createCall("99","失败",json.getJSONObject("InterBOSS").getString("TransIDO"));
    }

    /**
     * 创建订单xml
     * @return
     */
    public String createCall(String code,String msg,String orderId) {
        Element interBOSS = DocumentHelper.createElement("InterBOSS");

        Element bIPCode = DocumentHelper.createElement("BIPCode");
        bIPCode.addText("LLF8F006");
        interBOSS.add(bIPCode);
        Element activityCode = DocumentHelper.createElement("ActivityCode");
        activityCode.addText("T8012006");
        interBOSS.add(activityCode);
        Element aactionCode = DocumentHelper.createElement("ActionCode");
        aactionCode.addText("0");
        interBOSS.add(aactionCode);

        Element transIDO = DocumentHelper.createElement("TransIDO");
        transIDO.addText(orderId);
        interBOSS.add(transIDO);

        Element processTime = DocumentHelper.createElement("ProcessTime");
        processTime.addText(new DateUtils().toTimeStamp());
        interBOSS.add(processTime);

        Element response = DocumentHelper.createElement("Response");

        Element rspCode = DocumentHelper.createElement("RspCode");

        rspCode.setText(code);
        response.add(rspCode);

        Element Message = DocumentHelper.createElement("RspDesc");
        Message.addText(msg);
        response.add(Message);

        interBOSS.add(response);
        return interBOSS.asXML();
    }


    /**
     * 创建订单xml
     * @param mobile
     * @param datetimeText
     * @return
     */
    public String createOrderXml(String mobile,String datetimeText,String serialNum,String msgSender,Element svcCont,String bIPCodeStr ,String activity) {
        Element request = DocumentHelper.createElement("InterBOSS");

        Element origDomain = DocumentHelper.createElement("OrigDomain");
        request.add(origDomain);
        Element homeDomain = DocumentHelper.createElement("HomeDomain");
        request.add(homeDomain);

        Element bIPCode = DocumentHelper.createElement("BIPCode");
        bIPCode.addText(bIPCodeStr);
        request.add(bIPCode);

        Element bIPVer = DocumentHelper.createElement("BIPVer");
        bIPVer.addText("0100");
        request.add(bIPVer);
        //参见业务交易代码编码表
        Element activityCode = DocumentHelper.createElement("ActivityCode");
        activityCode.addText(activity);
        request.add(activityCode);
        //0：请求，1：应答
        Element actionCode = DocumentHelper.createElement("ActionCode");
        actionCode.addText("0");
        request.add(actionCode);

        Element routing = DocumentHelper.createElement("Routing");
        Element routeType = DocumentHelper.createElement("RouteType");
        routeType.addText("01");
        routing.add(routeType);
        Element routeValue = DocumentHelper.createElement("RouteValue");
        routeValue.addText(mobile);
        routing.add(routeValue);

        request.add(routing);

        Element procID = DocumentHelper.createElement("ProcID");
        procID.addText(serialNum);
        request.add(procID);
        Element transIDO = DocumentHelper.createElement("TransIDO");
        transIDO.addText(serialNum);
        request.add(transIDO);
        Element transIDH = DocumentHelper.createElement("TransIDH");
        request.add(transIDH);

        Element datetime = DocumentHelper.createElement("ProcessTime");
        //YYYYMMDDHHMMSS
        datetime.setText(datetimeText);
        request.add(datetime);
        Element response = DocumentHelper.createElement("Response");
        Element rspType = DocumentHelper.createElement("RspType");
        Element rspCode = DocumentHelper.createElement("RspCode");
        Element rspDesc = DocumentHelper.createElement("RspDesc");
        rspType.addText("");
        rspCode.addText("");
        rspDesc.addText("");
        response.add(rspType);
        response.add(rspCode);
        response.add(rspDesc);
        request.add(response);

        Element sPReserve = DocumentHelper.createElement("SPReserve");
        Element cutOffDay = DocumentHelper.createElement("CutOffDay");
        cutOffDay.addText("");
        sPReserve.add(cutOffDay);
        request.add(sPReserve);

        Element testFlag = DocumentHelper.createElement("TestFlag");
        testFlag.addText("0");
        request.add(testFlag);


        Element msgSenderText = DocumentHelper.createElement("MsgSender");
        msgSenderText.addText(msgSender);
        request.add(msgSenderText);

        Element MsgReceiver = DocumentHelper.createElement("MsgReceiver");
        MsgReceiver.addText("LLFF");
        request.add(MsgReceiver);

        Element svcContVer = DocumentHelper.createElement("SvcContVer");
        svcContVer.addText("0100");
        request.add(svcContVer);
        request.add(svcCont);
        return request.asXML();
    }
    private Element createOrderSvg(String mobile, String appId, String datetimeText,String incProdID){
        Element svcCont = DocumentHelper.createElement("SvcCont");

        Element syncInfoRep = DocumentHelper.createElement("SyncInfoRep");
        Element uProductInfo = DocumentHelper.createElement("UProductInfo");

        Element subscriberID = DocumentHelper.createElement("SubscriberID");
        //EC系统账号
        subscriberID.addText(appId);
        uProductInfo.add(subscriberID);
        Element oprCode = DocumentHelper.createElement("OprCode");
        //操作代码	01－定购限额   02—订购限量
        oprCode.addText("01");
        uProductInfo.add(oprCode);

        Element mobNum = DocumentHelper.createElement("MobNum");
        mobNum.addText(mobile);
        uProductInfo.add(mobNum);

        Element incProdIDText = DocumentHelper.createElement("IncProdID");
        incProdIDText.addText(incProdID);
        uProductInfo.add(incProdIDText);

        Element effective = DocumentHelper.createElement("Effective");
        //01：立即生效，有效期1个月
        //02：下月生效，有效期1个月
        effective.addText("01");
        uProductInfo.add(effective);
        Element effeCycle = DocumentHelper.createElement("EffeCycle");
        effeCycle.addText("");
        uProductInfo.add(effeCycle);
        Element limitFlow = DocumentHelper.createElement("LimitFlow");
        limitFlow.addText("");
        uProductInfo.add(limitFlow);

        Element oprTime = DocumentHelper.createElement("OprTime");
        //YYYYMMDDHHMMSS
        oprTime.setText(datetimeText);
        uProductInfo.add(oprTime);

        syncInfoRep.add(uProductInfo);
        svcCont.addText("<![CDATA["+syncInfoRep.asXML()+"]]>");
        return svcCont;
    }




    /**
     * 提单错误直接失败
     */
    private static Set<String> codesError = new HashSet<String>(){{

    }};
    /**
     */
    public void commitOrder(UpOrder order, UpShopInfo shop) {
        UpOrder product = this.upOrderService.findOrderProduct(order.getUporderuuid());
        if (product != null) {
            Map<String,String> headers = new HashMap<>();
            //String mobile, String appId, String datetimeText,String serialNum,String msgSender,String incProdID
            String xml = createOrderXml(order.getUpphonenum(),new DateUtils().toTimeStamp()
                    ,order.getUporderuuid(),shop.getUpkey(),createOrderSvg(order.getUpphonenum(),shop.getAppId(),new DateUtils().toTimeStamp(),
                           order.getUpShopPro().getProductCode()),"LLF8F002","T8012002");
            xml = xml.replace("&lt;","<").replace("&gt;",">");
            String res = HttpClient.postXmlHeader(shop.getOrderCommitAddress(),xml ,headers);
            logger.info("commithubei_result:" + xml +",phone:"+order.getUpphonenum()+",res:"+res);
            if (!StringUtils.isBlank(res) && !res.equals("500")) {
                try {
                    JSONObject json = JsonUtils.getJSONOBJCT();
                    if (!StringUtils.isBlank(res)) {
                        JsonUtils.iterateNodes(DocumentHelper.parseText(res).getRootElement(), json);

                        if(json.containsKey("InterBOSS") && json.getJSONObject("InterBOSS").containsKey("Response") &&
                                json.getJSONObject("InterBOSS").getJSONObject("Response").getString("RspCode").equals("00") &&
                           !StringUtils.isBlank(json.getJSONObject("InterBOSS").getString("SvcCont"))){

                            net.sf.json.JSONObject SvcCont = JsonUtils.getJSONOBJCT();
                            JsonUtils.iterateNodes(DocumentHelper.parseText(json.getJSONObject("InterBOSS").getString("SvcCont")).getRootElement(), SvcCont);
                            if(SvcCont != null && SvcCont.getJSONObject("OrderInfoRsp").getString("RspCode").equals("00") ){
                                upOrderService.updateUpOrderMsg(order,SvcCont.getJSONObject("OrderInfoRsp").getString("RspCode"),
                                        SvcCont.getJSONObject("OrderInfoRsp").getString("RspDesc"));
                            }else{
                                upOrderService.updateUpOrderArtificial(order,"", json.getJSONObject("InterBOSS").getJSONObject("Response").getString("RspCode"));
                            }
                        }else if (json.containsKey("InterBOSS") && !json.getJSONObject("InterBOSS").getJSONObject("Response").getString("RspCode").equals("00")) {
                            if(json.getJSONObject("InterBOSS").getJSONObject("Response").getString("RspCode").equals("98")){
                                order.setRemark(json.getJSONObject("InterBOSS").getJSONObject("Response").getString("RspDesc"));
                                RechargeRest.failtUpOrder.add(order);
                            }else{
                                //转人工
                                upOrderService.updateUpOrderArtificial(order,"", json.getJSONObject("InterBOSS").getJSONObject("Response").getString("RspDesc"));
                            }
                        }
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }
            } else {
                upOrderService.commitFailt(order,  Config.commitFailt);
                logger.info("commithubei_error" + order.getUpphonenum());
            }
        }
    }


    public static void main(String[] args) {
//        UpOrder order = new UpOrder();
//        order.setUporderuuid("xxxxx");
//        order.setUpphonenum("13554332222");
//
//        UpShopProduct product = new UpShopProduct();
//        product.setProductCode("G234974");
//        order.setUpShopPro(product);
//
//        UpShopInfo shop = new UpShopInfo();
//        shop.setAppId("7295450057824");
//        shop.setUpkey("23fa80310b28b0539715940bbdc1af3f");
//        shop.setOrderCommitAddress("http://119.23.55.151:8282/hbydllff_ws_outer/service/rest/llff/LLF8F002");
//
//        new HubeiRest().commitOrder(order,shop);
//        String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
//                "<InterBOSS><BIPCode>LLF8F006</BIPCode><ActivityCode>T8012006</ActivityCode><ActionCode>0</ActionCode><TransIDO>922ab97e10b5fb017e1d8fd5ad2a55</TransIDO><ProcessTime>20220103093026</ProcessTime><Response><RspCode>01</RspCode><RspDesc>无法查询到指定用户信息：[telnum]=[13554332222];</RspDesc></Response></InterBOSS>";
//
//        JSONObject json = JsonUtils.getJSONOBJCT();
//        try {
//            JsonUtils.iterateNodes(DocumentHelper.parseText(xml).getRootElement(), json);
//        } catch (DocumentException e) {
//            e.printStackTrace();
//        }
        Map<String,String> headers = new HashMap<>();
        String res = HttpClient.postXmlHeader("http://111.47.240.141/hbydllff_ws_outer/service/rest/llff/LLF8F002","<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
                "<InterBOSS>" +
                "   <OrigDomain></OrigDomain>" +
                "   <HomeDomain></HomeDomain>" +
                "   <BIPCode>LLF8F005</BIPCode>" +
                "   <BIPVer>0100</BIPVer>" +
                "   <ActivityCode>T8012005</ActivityCode>" +
                "   <ActionCode>0</ActionCode>" +
                "   <Routing>" +
                "      <RouteType>01</RouteType>" +
                "      <RouteValue>13669098773</RouteValue>" +
                "   </Routing>" +
                "   <ProcID>13669098773</ProcID>" +
                "   <TransIDO>13669098773</TransIDO>" +
                "   <TransIDH></TransIDH>" +
                "   <ProcessTime>2021221145100</ProcessTime>" +
                "   <Response>" +
                "      <RspType></RspType>" +
                "      <RspCode></RspCode>" +
                "      <RspDesc></RspDesc>" +
                "   </Response>" +
                "   <SPReserve>" +
                "      <CutOffDay></CutOffDay>" +
                "   </SPReserve>" +
                "   <TestFlag>0</TestFlag>" +
                "   <MsgSender>23fa80310b28b0539715940bbdc1af3f</MsgSender>" +
                "   <MsgReceiver>LLFF</MsgReceiver>" +
                "   <SvcContVer>0100</SvcContVer>" +
                "   <SvcCont><![CDATA[<QueryOrderReq><TransIDO>13669098773</TransIDO></QueryOrderReq>]]></SvcCont>" +
                "</InterBOSS>",headers);
        System.out.println(res);
    }
    public void queryOrder(UpOrder upOrder, UpShopInfo shopInfo) {
        if(upOrder != null ){
            UpOrder product = upOrderService.findOrderProduct(upOrder.getUporderuuid());
            if (product != null) {
                Map<String,String> headers = new HashMap<>();
                //String mobile,String datetimeText,String serialNum,String msgSender,Element svcCont,String bIPCodeStr
                String xml = createOrderXml(upOrder.getUpphonenum(),new DateUtils().toTimeStamp()
                        ,upOrder.getUporderuuid(),shopInfo.getUpkey(),createQuerySvg(upOrder.getUporderuuid()),"LLF8F005",
                        "T8012005");
                xml = xml.replace("&lt;","<").replace("&gt;",">");
                String res = HttpClient.postXmlHeader(shopInfo.getOrderStatusAddress(),xml,headers);
                logger.info("queryhubei:"+res+"data:"+token+",phone:"+upOrder.getUpphonenum());
                if(res != null){
                    JSONObject json = JsonUtils.getJSONOBJCT();
                    try {
                        if (!StringUtils.isBlank(res)) {
                            //00	成功
                            //01	等待BOSS反馈结果
                            //02	已同步到BOSS未生成账单
                            //03	已入账
                            //04	boss确认订单失败
                            //05	订单数量超过平台设定的限制，订单无效
                            //09	请求数据不存在
                            //98	校验错误
                            //99	未知错误
                            JsonUtils.iterateNodes(DocumentHelper.parseText(res).getRootElement(), json);

                            if(json.containsKey("InterBOSS") && json.getJSONObject("InterBOSS").containsKey("Response") &&
                                    json.getJSONObject("InterBOSS").getJSONObject("Response").getString("RspCode").equals("00")){

                                net.sf.json.JSONObject SvcCont = JsonUtils.getJSONOBJCT();
                                JsonUtils.iterateNodes(DocumentHelper.parseText(json.getJSONObject("InterBOSS").getString("SvcCont")).getRootElement(), SvcCont);
                                JSONObject jsonObject = SvcCont.getJSONObject("QueryOrderReq");
                                UpOrder order = upOrderService.findById(upOrder.getUporderuuid());

                                if( jsonObject.getString("RspCode").equals("03") &&order != null && order.getStatus() == Config.status[0] ){
                                    order.setRemark( json.getJSONObject("InterBOSS").getJSONObject("Response").getString("RspDesc"));
                                    RechargeRest.successUpOrder.add(order);
                                }else if( (jsonObject.getString("RspCode").equals("04") ||
                                        jsonObject.getString("RspCode").equals("05") ||
                                        jsonObject.getString("RspCode").equals("09")) && order != null && order.getStatus() == Config.status[0]){
                                    order.setRemark(json.getJSONObject("InterBOSS").getJSONObject("Response").getString("RspDesc"));
                                    RechargeRest.failtUpOrder.add(order);
                                }
                            }else{
                                logger.debug("queryhubei查询失败:"+upOrder.getUpphonenum());
                            }
                        }
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                }else{
                    logger.info("queryhubei order failt:"+upOrder.getUpphonenum());
                }
            }
        }else{
            logger.info("queryhubei order failt:"+upOrder.getUpphonenum());
        }
    }

    private Element createQuerySvg( String serialNum){
        Element svcCont = DocumentHelper.createElement("SvcCont");
        Element queryOrderReq = DocumentHelper.createElement("QueryOrderReq");
        Element transIDO = DocumentHelper.createElement("TransIDO");
        transIDO.addText(serialNum);
        queryOrderReq.add(transIDO);
        svcCont.addText("<![CDATA["+queryOrderReq.asXML()+"]]>");
        return svcCont;
    }


}
